"use strict"

let crypto = require("crypto")
let axios = require("axios")
let helper = {

	sendStat(arr, data) {
		return {c: arr[0], msg: arr[1], d: data}
	},

	md5(str) {
		let md5 = crypto.createHash("md5")
		md5.update(str)
		return md5.digest("hex").toUpperCase()  //32位大写
	},

	genRandomStr(len) {
		let arr = []
		for (let i = 0; i < len / 11; i++) {
			arr.push(Math.random().toString(36).slice(2))
		}
		return arr.join("").slice(0, len)
	},

	getToDay(time) {//now date
		let d = new Date(...arguments)
		d.setHours(0)
		d.setMinutes(0)
		d.setSeconds(0)
		d.setMilliseconds(0)
		return d.getTime()
	},
	/**
	 * 秒为单位, 需要绑定this
	 */
	todayRemaining() {
		return Math.floor((helper.getToDay() + 3600 * 24 * 1000 - Date.now()) / 1000)
	},
	/**
 * 
 * @param {string} str 
 */
	ipV4toInt(str) {
		/* --------------------- 
		作者：ou叮当 
		来源：CSDN 
		原文：https://blog.csdn.net/oujiangping/article/details/77715267 
		版权声明：本文为博主原创文章，转载请附上博文链接！ */
		var buf = str.split(".")
		if (buf.length != 4 || buf.find((v) => {
			return v < 0 || v > 255
		})) {
			let e = new Error()
			Object.assign(e, {msg: "ip错误"})
			throw e
		}
		return (parseInt(buf[0]) << 24 |
			parseInt(buf[1]) << 16 |
			parseInt(buf[2]) << 8 |
			parseInt(buf[3])) >>> 0

	},
	intToIp(INT) {
		if (INT < 0 || INT > 0xFFFFFFFF || INT == "") {
			// throw ("The number is not normal!");
			return ""
		}
		return (INT >>> 24) + "." + (INT >> 16 & 0xFF) + "." + (INT >> 8 & 0xFF) + "." + (INT & 0xFF)
	},
	async	getIP(ip) {
		let data = await axios.default.get("http://freeapi.ipip.net/" + ip, {
			timeout: 1000,
		})
		return data && data.data
	},
	/**
 * @template T
 * @param {T[]} arr 
 * @param {number} splitLen 
 */
	group(arr, splitLen) {
		if (!Array.isArray(arr)) {
			// console.log("传参必须是数组")
			return []
		}
		var result = []
		for (var i = 0; i < arr.length; i += splitLen) {
			result.push(arr.slice(i, i + splitLen))
		}
		return result
	},
	later(time) {
		if (time <= 0) {
			return Promise.resolve(time)
		}
		return new Promise(function (resolve) {
			setTimeout(function () {
				resolve(time)
			}, time)
		})
	}
}
module.exports = helper

// console.log(module.exports .md5("123213UUasdjj<>>>>")) 
// console.log(helper.getToDay())
// console.log(helper.ipV4toInt("182.149.160.223"))
// console.log(helper.todayRemaining()) 